let fs = require('fs')
let path = require('path')
let {StringDecoder} = require('string_decoder')
let decoder = new StringDecoder();
// 把buffer 转成字符串 保证不乱码
/**
 * HTTP/1.1 POST /user
 * Host: localhost:8080
 * User-Agent: curl/7.53.0
 * Accept: *
 * Content-Type: application/x-www-form-urlencoded
 * 
 * name=zfpx&age=9
 */
/**
 * http 服务器就是把请求头解析出来，把请求体传递给自己的监听函数
 * 把socket对象拆分成两个对象，一个请求对象，一个响应对象
 * HTTP是应用层协议，规定方法名 请求体 请求头 增加规范
 * TCP只管运输
 */
function parser(requestStream, requestListener){
    function onReadable(){
        let buf;
        let buffers = []
        while(null != (buf = requestStream.read())){
            buffers.push(buf)
            let str = decoder.write(buf)
            if(str.match(/\r\n\r\n/)){
                let result = Buffer.concat(buffers).toString()
                let values = result.split(/\r\n\r\n/);
                let headers = values.shift();
                let headerObj = parseHeader(headers)
                Object.assign(requestStream, headerObj)
                let body = values.join('\r\n\r\n')
                requestStream.removeListener('readable', onReadable)
                requestStream.unshift(Buffer.from(body))
                return requestListener(requestStream);
            } else{
                buffers.push(buf)
            }
        }
    }
    requestStream.on('readable', onReadable)  
}
function parseHeader(headerStr){
    let lines = headerStr.split(/\r\n/)
    let startLine = lines.shift()
    let starts = startLine.split(' ');
    let method = starts[0]
    let url = starts[1]
    let protocal = starts[2]
    let headers = {}
    lines.forEach(line => {
        let row = line.split(': ')
        headers[row[0]] = row[1]
    })
    return {headers, method, url, protocal}
}
let rs = fs.createReadStream(path.join(__dirname, 'req.txt'))
parser(rs, function(req){
    console.log(req.method) //POST
    console.log(req.url) // /user
    console.log(req.headers) 
    req.on("data", function(data){
        console.log(data.toString())
    })
    req.on('end', function(){
        console.log('处理结束')
    })
})
